/* =================================================
 * Package:			dk.iha.toksEditor
 * File:			InsertPatientData.java
 * Description:		This is the activity for which
 * 					is responsible for the insertion
 * 					of new patient TOKS values.
 * 
 * Responsible
 * =================================================
 * Name:			Jakob Sulby
 * Study number:	09136
 * 
 * Assistant(s)
 * =================================================
 * Name:			Bjarke Jensen
 * Study number:	09676
 */

package dk.iha.toksEditor;

import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class InsertPatientData extends Activity implements OnKeyListener, OnFocusChangeListener {	
	public static String myPrefs = "MY_PREFS";
	private double oxygenValue = 0, respirationValue = 0, saturationValue = 0, systolicValue = 0, diastolicValue = 0, pulseValue = 0, temperatureValue = 0;
	private int oxygenTOKSValue = 0, respirationTOKSValue = 0, saturationTOKSValue = 0, systolicTOKSValue = 0, diastolicTOKSValue = 0, pulseTOKSValue = 0, temperatureTOKSValue = 0, consciousnessTOKSValue = 0;
	private String consciousnessValue;
	public AlertDialog dialog;
	private Cursor result;
	private EditText oxygenEditBox, respirationEditBox, saturationEditBox, systolicEditBox, diastolicEditBox, pulseEditBox, temperatureEditBox;
	private Spinner spin;
	private User mUser;
	private Patient mPatient;
	private DataBaseConnection mdb;
	private DBAdapter localDB;
	private Boolean fromUnfinished = false;
	private TOKS oldData;
	private Boolean commentOpen = false;
	
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.insert_patient_view);
		
		//Initiates variables.
		mPatient = (Patient) getIntent().getSerializableExtra("patient");
		mUser = new User(this);
		mdb = new DataBaseConnection(mUser);
		localDB = new DBAdapter(this);
		fromUnfinished = getIntent().getBooleanExtra("fromUnfinished", false);
		oldData = new TOKS();
		
		//Starting a background check on the user stats
		IsPatientAFavoritAsyncTask mTask = new IsPatientAFavoritAsyncTask();
		mTask.execute("");
		
		//Adding relations to GUI widgets	
		setTitle(getString(R.string.app_name) + " - " + mUser.getUserName());
		
	    oxygenEditBox = (EditText)findViewById(R.id.oxygenEditText);
	    respirationEditBox = (EditText)findViewById(R.id.respirationEditText);
	    saturationEditBox = (EditText)findViewById(R.id.saturationEditText);
	    systolicEditBox = (EditText)findViewById(R.id.bloodPressureSystolicEditText);
	    diastolicEditBox = (EditText)findViewById(R.id.bloodPressureDiastolicEditText);
	    pulseEditBox = (EditText)findViewById(R.id.pulseEditText);
	    temperatureEditBox = (EditText)findViewById(R.id.temperatureEditText);
	    
	    oxygenEditBox.setOnKeyListener(this);
	    respirationEditBox.setOnKeyListener(this);
	    saturationEditBox.setOnKeyListener(this);
	    systolicEditBox.setOnKeyListener(this);
	    diastolicEditBox.setOnKeyListener(this);
	    pulseEditBox.setOnKeyListener(this);
	    temperatureEditBox.setOnKeyListener(this);
	    
	    oxygenEditBox.setOnFocusChangeListener(this);
	    respirationEditBox.setOnFocusChangeListener(this);
	    saturationEditBox.setOnFocusChangeListener(this);
	    systolicEditBox.setOnFocusChangeListener(this);
	    diastolicEditBox.setOnFocusChangeListener(this);
	    pulseEditBox.setOnFocusChangeListener(this);
	    temperatureEditBox.setOnFocusChangeListener(this);
	    
	    spin = (Spinner) findViewById(R.id.patientConsciousnessSelector);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource (this, R.array.patientConsciousnessSelectorValues, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spin.setAdapter(adapter);
	    
	    spin.setOnItemSelectedListener(new OnItemSelectedListener() {
	        @Override
	        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
	            calculateTOKS(selectedItemView);
	            spin.requestFocus();
	        }

	        @Override
	        public void onNothingSelected(AdapterView<?> parentView) {
	            // your code here
	        }
	    });

	    //Setting the last texts on the GUI
	    ((TextView)findViewById(R.id.patientName)).setText(mPatient.getName());
	    ((TextView)findViewById(R.id.patientCPR)).setText(mPatient.getEasyCPR());
	    
	    SharedPreferences settings = getSharedPreferences(myPrefs, 0);
	    settings = getSharedPreferences(myPrefs, 0);
	    Boolean dialogSeen  = settings.getBoolean("dialogSeen", false);
	    
	    //Is there an saved value for this patient in the local database?
	    try 
	    {
	    	localDB.open();
	    	result = localDB.getPatient(mPatient.getCPR());
	    	
			    if(!fromUnfinished && !dialogSeen)
			    {
			    	//Checking in local database if the patient has unfinished tasks.
			    	AlertDialog ad = new AlertDialog.Builder(this).create();  
		    		ad.setTitle(getString(R.string.patientHasSavedObservationTitle));  
		    		ad.setMessage(getString(R.string.patientHasSavedObservationDescription));  
		    		ad.setIcon(R.drawable.ic_ipd_existing_p_dialog); 
		    		ad.setButton(getString(R.string.generalOKBtn), new DialogInterface.OnClickListener() {  
		    	      public void onClick(DialogInterface dialog, int which) 
		    	      {				    	    	  
		    	    	  loadSavedData();
		    	    	  return;
		    	    } });
		    		ad.setButton2(getString(R.string.generalCancelBtn), new DialogInterface.OnClickListener() {  
		      	      public void onClick(DialogInterface dialog, int which) 
		      	      {
		      	    	  return;
		      	    } });
		    		
		    		ad.setOnDismissListener(new DialogInterface.OnDismissListener() {
						
						@Override
						public void onDismiss(DialogInterface dialog) {
							SharedPreferences settings = getSharedPreferences(myPrefs, 0);
			    	    	  settings = getSharedPreferences(myPrefs, 0);
			    	    	  SharedPreferences.Editor editor = settings.edit();
			    	    	  editor.putBoolean("dialogSeen", true);
			    	    	  editor.commit();							
						}
					});
		    		
		    		ad.show();	
		    }
		    	
		    else
		    {
		    	loadSavedData();
		    }
			    
		} 
	    
	    //Catch if there wans't any saved data.
	    catch (Exception e)
	    {
	    	e.printStackTrace();
		}
	    
	    //Start background thread for getting last data from the external database.
	    DatabaseCommunication dbGetOldData = new DatabaseCommunication();
	    dbGetOldData.execute("getOldData");
	    
	    //Start background thread for getting max toks value for patient
	    GetMaxToksAsyncTask dbGetMaxToks = new GetMaxToksAsyncTask();
	    dbGetMaxToks.execute("");
	    
	    //Show welcome message
	    doTalk(null);
	}
	
	@Override
	protected void onResume() {
		localDB.open();
		
		//Set keep screen on = on/off
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		if(prefs.getBoolean("checkboxPref", false))
		{
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		
		else
		{
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		}
		super.onResume();
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedState) {
		super.onRestoreInstanceState(savedState);
		
		//Shall open dialog?
		commentOpen = savedState.getBoolean("commentBool", false);
		if(commentOpen)
		{
			findViewById(R.id.WriteCommentImage).performClick();
			((EditText)dialog.findViewById(R.id.commentEditText)).setText(savedState.getString("commentString"));
		}
	}
	 
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		//Is there written a new comment?
		outState.putBoolean("commentBool", commentOpen);
		if(commentOpen)
			outState.putString("commentString", ((EditText)dialog.findViewById(R.id.commentEditText)).getText().toString());
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.insert_patient_data_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		
		//Are you allowed to save? Then show the right save button.
		if(respirationEditBox.getText().length() != 0 && systolicEditBox.getText().length() != 0 && pulseEditBox.getText().length() != 0 && temperatureEditBox.getText().length() != 0 && systolicEditBox.getText().length() != 0)
		{	
			menu.getItem(0).setIcon(R.drawable.ic_ipd_save);
			menu.getItem(0).setEnabled(true);
		}
		
		else
		{
			menu.getItem(0).setIcon(R.drawable.ic_ipd_nosave);
			menu.getItem(0).setEnabled(false);
		}
		
		//Is the patient your favorit? Then show the comment icon.
		if(!mPatient.getIsFavorite())
		{
			menu.getItem(2).setEnabled(true);
			menu.getItem(2).setVisible(true);
			menu.getItem(3).setEnabled(false);
			menu.getItem(3).setVisible(false);
		}
		
		else
		{
			menu.getItem(2).setEnabled(false);
			menu.getItem(2).setVisible(false);
			menu.getItem(3).setEnabled(true);
			menu.getItem(3).setVisible(true);
		}
		
		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{	
		//Handle item selection
	    switch (item.getItemId()) 
	    {	            
	        case R.id.patientMenuSave:
	        	savePatientNote();
	            return true;
	            
	        case R.id.patientMenuCancel:
	        	cancelPatientNote();
	            return true;
	            
	        case R.id.patientMenuAddFavorit:
	        	addThisPatientToMyFavorits();
	            return true;
	            
	        case R.id.patientMenuRemoveFavorit:
	        	removeThisPatientFromMyFavorits();
	            return true;
	            
	        case R.id.patientMenuCallDoctor:
	        	callDoctor();
	            return true;
	            
	        default:
	        	return super.onMenuItemSelected(featureId, item);
	    }	
	}
	
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) 
	{
		calculateTOKS(v);
		return false;
	}
	
	@Override
	public void onBackPressed() {
		SharedPreferences settings = getSharedPreferences(myPrefs, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("dialogSeen", false);
		editor.commit();
		
		//Save patient locally?
		if(hasMadeChanges())
		{
			addTOKSValuesToPatient();
			savePatientLocally(mPatient);
			localDB.close();
		}
		
		super.onBackPressed();
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) 
	{
		if(hasFocus)
			doTalk(v);
		else
			calculateTOKS(v);
	}
	
	/**
	 * Find out if there is any changes to save.
	 * @return Returns true or false.
	 */
	private boolean hasMadeChanges()
	{
		if(!oxygenEditBox.getText().toString().contentEquals("") ||
				!respirationEditBox.getText().toString().contentEquals("") ||
				!saturationEditBox.getText().toString().contentEquals("") ||
				!systolicEditBox.getText().toString().contentEquals("") ||
				!diastolicEditBox.getText().toString().contentEquals("") ||
				!pulseEditBox.getText().toString().contentEquals("") ||
				!temperatureEditBox.getText().toString().contentEquals("") ||
				spin.getSelectedItemPosition() > 0)
			return true;
		return false;
	}
	
	/**
	 * Loads saved data for the specified patient into this local patient.
	 */
	private void loadSavedData()
	{
		TOKS tempTOKS = new TOKS();
  	  
		// Make sure there is at least one row.
		if (result.moveToFirst()) 
		{
			// Iterate over each cursor.
			do 
			{
				mPatient.setNote(result.getString(3));
				tempTOKS.setBloodPressureDiastolic(result.getInt(10));
				tempTOKS.setBloodPressureSystolic(result.getInt(6));
				tempTOKS.setConsciousness(result.getString(11));				
				tempTOKS.setDate(new Date(Long.parseLong(result.getString(4))));
				tempTOKS.setHeartRate(result.getInt(7));
				tempTOKS.setOxygenLitersPerMinute(result.getDouble(12));
				tempTOKS.setRespirationFrequency(result.getInt(5));
				tempTOKS.setSaturation(result.getInt(9));
				tempTOKS.setTemperature(result.getDouble(8));
			} while(result.moveToNext());
			
			mPatient.setTOKS(tempTOKS);
			
			if(mPatient.getTOKS().getOxygenLitersPerMinute() != 0.0)
				oxygenEditBox.setText(mPatient.getTOKS().getOxygenLitersPerMinute().toString());
			
			if(mPatient.getTOKS().getRespirationFrequency() != 0)
				respirationEditBox.setText(mPatient.getTOKS().getRespirationFrequency().toString());
			
			if(mPatient.getTOKS().getSaturation() != 0)
				saturationEditBox.setText(mPatient.getTOKS().getSaturation().toString());
			
			if(mPatient.getTOKS().getBloodPressureSystolic() != 0)
				systolicEditBox.setText(mPatient.getTOKS().getBloodPressureSystolic().toString());
			
			if(mPatient.getTOKS().getBloodPressureDiastolic() != 0)
				diastolicEditBox.setText(mPatient.getTOKS().getBloodPressureDiastolic().toString());
			
			if(mPatient.getTOKS().getHeartRate() != 0)
				pulseEditBox.setText(mPatient.getTOKS().getHeartRate().toString());
			
			if(mPatient.getTOKS().getTemperature() != 0.0)
				temperatureEditBox.setText(mPatient.getTOKS().getTemperature().toString());
			
			int spinnerPosition = 0;
			
			if(mPatient.getTOKS().getConsciousness().contentEquals("NO_REACTION"))
			{
				spinnerPosition = 4;
			}
			
			else if(mPatient.getTOKS().getConsciousness().contentEquals("REACTS_TO_PAIN"))
			{
				spinnerPosition = 3;
			}
			
			else if(mPatient.getTOKS().getConsciousness().contentEquals("REACTS_TO_SPEAK"))
			{
				spinnerPosition = 2;
			}
			
			else if(mPatient.getTOKS().getConsciousness().contentEquals("HABITUEL"))
			{
				spinnerPosition = 1;
			}
			
			else if(mPatient.getTOKS().getConsciousness().contentEquals("AGITATED"))
			{
				spinnerPosition = 0;
			}
			
			spin.setSelection(spinnerPosition);
			
			if(mPatient.getNote().length() != 0)
				((TextView)findViewById(R.id.smileyTalk)).setText(mPatient.getNote());
			
			else
				((TextView)findViewById(R.id.smileyTalk)).setText(getString(R.string.patientNoCommentsToPatient));
			
			//Calculating new TOKS value.
			heavyTOKSCalculation();
		}
	}
	
	/**
	 * Save the patient to the external database. It fails it will save the patient locally.
	 * It starts an async task to do the work and returns immediately, so the user can continue on a new patient.
	 */
	public void savePatientNote()
	{
		addTOKSValuesToPatient();
		DatabaseCommunication comm = new DatabaseCommunication();
		comm.execute("saveToExternalDatabase");
		
		Intent i = new Intent();
		setResult(RESULT_OK, i);
		
		SharedPreferences settings = getSharedPreferences(myPrefs, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("dialogSeen", false);
		editor.commit();
		
		finish();
	}
	
	/**
	 * This will close the view.
	 */
	public void cancelPatientNote()
	{
		localDB.close();
		Intent i = new Intent();
		setResult(RESULT_CANCELED, i);
		
		SharedPreferences settings = getSharedPreferences(myPrefs, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("dialogSeen", false);
		editor.commit();
		
		finish();
	}
	
	/**
	 * This method will start a new async task to save the current patient as a favorit.
	 */
	private void addThisPatientToMyFavorits()
	{
		DatabaseCommunication comm = new DatabaseCommunication();
		comm.execute("addToFavorites");
		mPatient.setIsFavorite(true);
		((ImageView)findViewById(R.id.WriteCommentImage)).setVisibility(View.VISIBLE);
	}
	
	/**
	 * This will remove the current patient from the favorit list.
	 */
	private void removeThisPatientFromMyFavorits()
	{
		DatabaseCommunication comm = new DatabaseCommunication();
		comm.execute("removeFromFavorites");
		mPatient.setIsFavorite(false);
		((ImageView)findViewById(R.id.WriteCommentImage)).setVisibility(View.GONE);
	}
	
	/**
	 * This will add current TOKS values to the current patient.
	 */
	private void addTOKSValuesToPatient()
	{
		TOKS toks = new TOKS();
		
		if(oxygenEditBox.getText().length() != 0)
			toks.setOxygenLitersPerMinute(Double.parseDouble(oxygenEditBox.getText().toString()));
		
		if(respirationEditBox.getText().length() != 0)
			toks.setRespirationFrequency(Integer.parseInt(respirationEditBox.getText().toString()));
		
		if(saturationEditBox.getText().length() != 0)
			toks.setSaturation(Integer.parseInt(saturationEditBox.getText().toString()));
		
		if(systolicEditBox.getText().length() != 0)
			toks.setBloodPressureSystolic(Integer.parseInt(systolicEditBox.getText().toString()));
		
		if(diastolicEditBox.getText().length() != 0)
			toks.setBloodPressureDiastolic(Integer.parseInt(diastolicEditBox.getText().toString()));
		
		if(pulseEditBox.getText().length() != 0)
			toks.setHeartRate(Integer.parseInt(pulseEditBox.getText().toString()));
		
		if(temperatureEditBox.getText().length() != 0)
			toks.setTemperature(Double.parseDouble(temperatureEditBox.getText().toString()));
		
		consciousnessValue = spin.getSelectedItem().toString();
		
		if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[4]))
		{
			toks.setConsciousness("NO_REACTION");
		}
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[3]))
		{
			toks.setConsciousness("REACTS_TO_PAIN");
		}		
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[2]))
		{
			toks.setConsciousness("REACTS_TO_SPEAK");
		}
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[1]))
		{
			toks.setConsciousness("HABITUEL");
		}
		
		else
		{
			toks.setConsciousness("AGITATED");
		}		
		
		toks.setDate(new Date(System.currentTimeMillis()));
		toks.setTotalScore(oxygenTOKSValue + respirationTOKSValue + saturationTOKSValue + systolicTOKSValue + diastolicTOKSValue + pulseTOKSValue + temperatureTOKSValue + consciousnessTOKSValue);//3263
		
		mPatient.setTOKS(toks);
		mPatient.setLastUpdated(new Date());
	}
	
	/**
	 * This will calculate the TOKS value for a specific EditText.
	 * @param v The EditText with the value.
	 */
	private void calculateTOKS(View v)
	{		
		if(v == oxygenEditBox)
		{
			oxygenValue = 0;
		}
		
		else if(v == respirationEditBox)
		{
			if(respirationEditBox.getText().length() > 0)
			{
				respirationValue = Double.parseDouble(respirationEditBox.getText().toString().replace(',', '.'));
				
				if(respirationValue < 6 || 26 <= respirationValue)
					respirationTOKSValue = 3;
				
				else if(21 <= respirationValue && respirationValue < 26)		
					respirationTOKSValue = 2;
				
				else if((6 <= respirationValue && respirationValue < 10) || (17 <= respirationValue && respirationValue < 21))		
					respirationTOKSValue = 1;
				
				else
					respirationTOKSValue = 0;
			}
			
			else
				respirationTOKSValue = 0;
		}
		
		else if(v == saturationEditBox)
		{
			if(saturationEditBox.getText().length() > 0)
			{
				saturationValue = Double.parseDouble(saturationEditBox.getText().toString().replace(',', '.'));
				
				if(saturationValue < 85)
					saturationTOKSValue = 3;
				
				else if(85 <= saturationValue && saturationValue < 90)		
					saturationTOKSValue = 2;
				
				else if(90 <= saturationValue && saturationValue < 93)		
					saturationTOKSValue = 1;
				
				else
					saturationTOKSValue = 0;
			}
			
			else
				saturationTOKSValue = 0;
		}
		
		else if(v == systolicEditBox)
		{
			systolicTOKSValue = 0;
		}
		
		else if(v == diastolicEditBox)
		{
			diastolicTOKSValue = 0;
		}
		
		else if(v == pulseEditBox)
		{
			if(pulseEditBox.getText().length() > 0)
			{
				pulseValue = Double.parseDouble(pulseEditBox.getText().toString().replace(',', '.'));
				
				if(pulseValue < 40 || 130 <= pulseValue)
					pulseTOKSValue = 3;
				
				else if(110 <= pulseValue && pulseValue < 130)		
					pulseTOKSValue = 2;
				
				else if((40 <= pulseValue && pulseValue < 50) || (90 <= pulseValue && pulseValue < 110))		
					pulseTOKSValue = 1;
				
				else
					pulseTOKSValue = 0;
			}
			
			else
				pulseTOKSValue = 0;
		}
		
		else if(v == temperatureEditBox)
		{
			if(temperatureEditBox.getText().length() > 0)
			{
				temperatureValue = Double.parseDouble(temperatureEditBox.getText().toString().replace(',', '.'));
				
				if(temperatureValue < 34 || 40 <= temperatureValue)
					temperatureTOKSValue = 3;
				
				else if((34 <= temperatureValue && temperatureValue < 36) || (39 <= temperatureValue && temperatureValue < 40))
					temperatureTOKSValue = 2;
				
				else if(38 <= temperatureValue && temperatureValue < 39)		
					temperatureTOKSValue = 1;
				
				else
					temperatureTOKSValue = 0;
			}
			
			else
				temperatureTOKSValue = 0;
		}
		
		consciousnessValue = spin.getSelectedItem().toString();
		
		if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[4]))
		{
			consciousnessTOKSValue = 3;
			consciousnessValue = "NO_REACTION";
		}
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[3]))
		{
			consciousnessTOKSValue = 2;
			consciousnessValue = "REACTS_TO_PAIN";
		}		
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[2]))
		{
			consciousnessTOKSValue = 1;
			consciousnessValue = "REACTS_TO_SPEAK";
		}
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[1]))
		{
			consciousnessTOKSValue = 1;
			consciousnessValue = "HABITUEL";
		}
		
		else
		{
			consciousnessTOKSValue = 0;
			consciousnessValue = "AGITATED";
		}
		
		//Update total TOKS value field.
		((TextView)findViewById(R.id.TOKSValue)).setText(Integer.toString(oxygenTOKSValue + respirationTOKSValue + saturationTOKSValue + systolicTOKSValue + diastolicTOKSValue + pulseTOKSValue + temperatureTOKSValue + consciousnessTOKSValue));
	}
	
	/**
	 * This will calculate the TOKS value from all fields and publish it to the TOKS value field.
	 */
	private void heavyTOKSCalculation()
	{
		oxygenValue = 0;
		systolicTOKSValue = 0;
		diastolicTOKSValue = 0;
		
		if(respirationEditBox.getText().length() > 0)
		{
			respirationValue = Double.parseDouble(respirationEditBox.getText().toString().replace(',', '.'));
			
			if(respirationValue < 6 || 26 <= respirationValue)
				respirationTOKSValue = 3;
			
			else if(21 <= respirationValue && respirationValue < 26)		
				respirationTOKSValue = 2;
			
			else if((6 <= respirationValue && respirationValue < 10) || (17 <= respirationValue && respirationValue < 21))		
				respirationTOKSValue = 1;
			
			else
				respirationTOKSValue = 0;
		}
		
		else
			respirationTOKSValue = 0;
	
		if(saturationEditBox.getText().length() > 0)
		{
			saturationValue = Double.parseDouble(saturationEditBox.getText().toString().replace(',', '.'));
			
			if(saturationValue < 85)
				saturationTOKSValue = 3;
			
			else if(85 <= saturationValue && saturationValue < 90)		
				saturationTOKSValue = 2;
			
			else if(90 <= saturationValue && saturationValue < 93)		
				saturationTOKSValue = 1;
			
			else
				saturationTOKSValue = 0;
		}
		
		else
			saturationTOKSValue = 0;
	
		if(pulseEditBox.getText().length() > 0)
		{
			pulseValue = Double.parseDouble(pulseEditBox.getText().toString().replace(',', '.'));
			
			if(pulseValue < 40 || 130 <= pulseValue)
				pulseTOKSValue = 3;
			
			else if(110 <= pulseValue && pulseValue < 130)		
				pulseTOKSValue = 2;
			
			else if((40 <= pulseValue && pulseValue < 50) || (90 <= pulseValue && pulseValue < 110))		
				pulseTOKSValue = 1;
			
			else
				pulseTOKSValue = 0;
		}
		
		else
			pulseTOKSValue = 0;
	
		if(temperatureEditBox.getText().length() > 0)
		{
			temperatureValue = Double.parseDouble(temperatureEditBox.getText().toString().replace(',', '.'));
			
			if(temperatureValue < 34 || 40 <= temperatureValue)
				temperatureTOKSValue = 3;
			
			else if((34 <= temperatureValue && temperatureValue < 36) || (39 <= temperatureValue && temperatureValue < 40))
				temperatureTOKSValue = 2;
			
			else if(38 <= temperatureValue && temperatureValue < 39)		
				temperatureTOKSValue = 1;
			
			else
				temperatureTOKSValue = 0;
		}
		
		else
			temperatureTOKSValue = 0;

		consciousnessValue = spin.getSelectedItem().toString();
		
		if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[4]))
		{
			consciousnessTOKSValue = 3;
			consciousnessValue = "NO_REACTION";
		}
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[3]))
		{
			consciousnessTOKSValue = 2;
			consciousnessValue = "REACTS_TO_PAIN";
		}		
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[2]))
		{
			consciousnessTOKSValue = 1;
			consciousnessValue = "REACTS_TO_SPEAK";
		}
		
		else if(consciousnessValue.contentEquals(getResources().getStringArray(R.array.patientConsciousnessSelectorValues)[1]))
		{
			consciousnessTOKSValue = 1;
			consciousnessValue = "HABITUEL";
		}
		
		else
		{
			consciousnessTOKSValue = 0;
			consciousnessValue = "AGITATED";
		}
		
		((TextView)findViewById(R.id.TOKSValue)).setText(Integer.toString(oxygenTOKSValue + respirationTOKSValue + saturationTOKSValue + systolicTOKSValue + diastolicTOKSValue + pulseTOKSValue + temperatureTOKSValue + consciousnessTOKSValue));
	}
	
	/**
	 * This method is posting methods to the screen (the smiley dialog box)
	 * @param v The view in focus.
	 */
	private void doTalk(View v)
	{
		TextView smileyTalk = (TextView)findViewById(R.id.smileyTalk);
		
		
		if(v == oxygenEditBox)
		{
			smileyTalk.setText(getString(R.string.patientOldValueStartSentence) + " " + oldData.getOxygenLitersPerMinute().toString() + " " + getString(R.string.patientOxygenHint) + ".");
		}
		
		else if(v == respirationEditBox)
		{
			smileyTalk.setText(getString(R.string.patientOldValueStartSentence) + " " + oldData.getRespirationFrequency().toString() + " " + getString(R.string.patientRespirationHint));
		}
		
		else if(v == saturationEditBox)
		{
			smileyTalk.setText(getString(R.string.patientOldValueStartSentence) + " " + oldData.getSaturation().toString() + " " + getString(R.string.patientSaturationHint) + ".");
		}
		
		else if(v == systolicEditBox)
		{
			smileyTalk.setText(getString(R.string.patientOldValueStartSentence) + " " + oldData.getBloodPressureSystolic().toString() + " " + getString(R.string.patientBloodPressureSystolicHint) + ".");
		}
		
		else if(v == diastolicEditBox)
		{
			smileyTalk.setText(getString(R.string.patientOldValueStartSentence) + " " + oldData.getBloodPressureDiastolic().toString() + " " + getString(R.string.patientBloodPressureDiastolicHint) + ".");
		}
		
		else if(v == pulseEditBox)
		{
			smileyTalk.setText(getString(R.string.patientOldValueStartSentence) + " " + oldData.getHeartRate().toString() + " " + getString(R.string.patientPulseHint) + ".");
		}
		
		else if(v == temperatureEditBox)
		{
			smileyTalk.setText(getString(R.string.patientOldValueStartSentence) + " " + oldData.getTemperature().toString() + " " + getString(R.string.patientTemperatureHint) + ".");
		}
		
		else
		{
			Random index = new Random();
			String[] sa = (getResources().getStringArray(R.array.PatientWelcomeMessages));
			smileyTalk.setText(sa[index.nextInt(5)]);
		}
	}

	/**
	 * Changes the smileys talk to the comment for the patient.
	 * @param Takes a view.
	 */
	public void onReadCommentClicked(View v)
	{
		if(mPatient.getNote().length() != 0)
			((TextView)findViewById(R.id.smileyTalk)).setText(mPatient.getNote());
		
		else
			((TextView)findViewById(R.id.smileyTalk)).setText(getString(R.string.patientNoCommentsToPatient));
	}
	
	/**
	 * Opens a dialog to add a comment to the current patient.
	 * @param Takes a view.
	 */
	public void onWriteCommentClicked(View v)
	{
		commentOpen = true;
		LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.add_comment_to_patient_dialog, null);
        dialog = new AlertDialog.Builder(this)
            .setIcon(R.drawable.write_comment_white_icon)
            .setTitle(R.string.patientWriteCommentDialogTitle)
            .setView(textEntryView)
            .setPositiveButton(R.string.generalSaveBtn, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface mdialog, int whichButton) 
                {
                	mPatient.setNote(((EditText)dialog.findViewById(R.id.commentEditText)).getText().toString());
                	commentOpen = false;
                }
            })
            .setNegativeButton(R.string.generalCancelBtn, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) 
                {
                	commentOpen = false;
                }
            })
            .create();
        
        dialog.show();

        //The last code here will show the soft keyboard.
        (new Handler()).postDelayed(new Runnable() {

            public void run() 
            {
		        EditText comments = (EditText)dialog.findViewById(R.id.commentEditText);
		
		        comments.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
		        comments.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
            }
        }, 0);
	}
	
	/**
	 * This will call an intent which starts a calling activity.
	 */
	private void callDoctor()
	{
		Intent callIntent = new Intent(Intent.ACTION_DIAL);
		startActivity(callIntent);
	}
	
	/**
	 * This will save the patient locally.
	 * @param patient
	 */
	private void savePatientLocally(Patient patient)
	{
		localDB.updatePatient(patient);
	}
	
	/**
	 * This is a async task which will do all the communication with the external database.
	 * @author Jakob Sulby
	 */
	private class DatabaseCommunication extends AsyncTask<String, Integer, Boolean>
	{
		private boolean completed = true;
		private String job = "";
		
		@Override
		protected Boolean doInBackground(String... params) 
		{
			if(params[0].toString().contains("saveToExternalDatabase"))
			{
				job = "saveToExternalDatabase";
				
				try 
				{
					mdb.addTOKS(mPatient);
					if(mPatient.getNote().length() > 1)
						mdb.updateNoteFavoritePatient(mPatient);
				}
				
				catch (Exception e) 
				{
					e.printStackTrace();
					
					
					try {
						localDB.updatePatient(mPatient);
					} catch (Exception e1) {
						localDB.open();
						localDB.updatePatient(mPatient);
						localDB.close();
					}
					completed = false;
				}
			} 
			
			else if(params[0].toString().contains("addToFavorites"))
			{
				job = "addToFavorites";
				
				try 
				{
					mdb.addToFavorites(mPatient);
				}
				
				catch (Exception e) 
				{
					e.printStackTrace();
					completed = false;
				}
			}
			
			else if(params[0].toString().contains("removeFromFavorites"))
			{
				job = "removeFromFavorites";
				
				try 
				{
					mdb.deleteFromFavorites(mPatient);
				}
				
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}
			
			else if(params[0].toString().contains("getOldData"))
			{
				job = "getOldData";
				
				try 
				{
					ArrayList<TOKS> result = mdb.getTOKSHistory(mPatient, 1);
					oldData = result.get(0);
				}
				
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(job.contentEquals("saveToExternalDatabase"))
			{
				if(completed)
				{
					if(!localDB.removePatient(mPatient))
	        		{
	        			localDB.open();
	        			localDB.removePatient(mPatient);
	        			localDB.close();
	        		}
					
					Toast.makeText(getApplicationContext(), getString(R.string.patientMesagesSaved), Toast.LENGTH_SHORT).show();
				}
				
				else
				{
					Toast.makeText(getApplicationContext(), getString(R.string.patientMesagesNotSaved), Toast.LENGTH_SHORT).show();
				}
			}
			
			else if(!completed)
			{
				Toast.makeText(getApplicationContext(), getString(R.string.patientMessageFavoritsError), Toast.LENGTH_SHORT).show();
			}
			
			super.onPostExecute(result);
		}		
	}
	
	/**
	 * This will start an async task to test if the current patient is a favorit.
	 * @author Jakob Sulby
	 */
	private class IsPatientAFavoritAsyncTask extends AsyncTask<String, Integer, Boolean>
	{

		@Override
		protected Boolean doInBackground(String... params) {
			mPatient.setIsFavorite(mdb.isPatientFavorite(mPatient));
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(!mPatient.getIsFavorite())
			{
				((ImageView)findViewById(R.id.WriteCommentImage)).setVisibility(View.GONE);
			}
			
			else
			{
				((ImageView)findViewById(R.id.WriteCommentImage)).setVisibility(View.VISIBLE);
			}
			super.onPostExecute(result);
		}	
	}
	
	/**
	 * This will start an async task to get the max TOKS value for the current patient.
	 * @author Jakob Sulby
	 */
	private class GetMaxToksAsyncTask extends AsyncTask<String, Integer, Boolean>
	{
		private Integer maxToks = 0;
		private MaxToksDBAdapter maxToksDB;
		
		@Override
		protected void onPreExecute() {
			maxToksDB = new MaxToksDBAdapter(getApplicationContext());
			maxToksDB.openReadOnly();
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			try {
				Cursor c = maxToksDB.getMaxToks(mPatient.getCPR());
				
				if(c != null)
				{
					maxToks = Integer.parseInt(c.getString(2));
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			maxToksDB.close();
			((TextView)findViewById(R.id.TOKSValueMax)).setText(maxToks.toString());
			super.onPostExecute(result);
		}	
	}
}
